#!/usr/local/bin/python
# -*- coding: utf-8 -*-
import json

from PyQt5 import QtWidgets
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QDialog, QAbstractItemView, QTableWidgetItem, QCheckBox, QWidget, QHBoxLayout, \
    QTreeWidgetItem, QMessageBox

import ConfigManage
import initBillParseDialog
from data_alchemy.bill_parse_regulation_alchemy import BillParseRegulationAlchemy
from initLogger import logger
#from ui.BillParseUI_b import Ui_BillParseDialog
from ui.BillParseUI import Ui_BillParseDialog


class BillParseDialog(QDialog,  Ui_BillParseDialog):
    '''
    类的功能：账单解析规则添加对话框。
    '''

    def __init__(self, parent, tableHeaderLabels, tableKeys, selectItem):
        QDialog.__init__(self, parent)



        self.setupUi(self)
        # 单独移除帮助按钮
        self.setWindowFlag(Qt.WindowContextHelpButtonHint, False)

        self.currentVoucherTextEdit = None
        self.tableValesList =[]
        for selectItemField  in selectItem:
            self.tableValesList.append(selectItemField.text().strip('\t'))

        self.tableKeysList = tableKeys
        self.tableHeaderLabelsList = tableHeaderLabels

        #self.year_comboBox.addItems(init.YEAR_NAME_LIST)
        self.priority_comboBox.addItems(initBillParseDialog.RULE_PRIORITY_LIST)
        self.priority_comboBox.setCurrentIndex(2)

        self.initBillTableUI()
        self.initBillTableData()

    def initBillTableUI(self):
        '''
        函数功能：对异常账单表的UI进行初始化
        :return:
        '''
        logger.debug("call nitBillTableUI function")

        self.bill_parse_tableWidget

        self.bill_parse_tableWidget.setRowCount(len(self.tableHeaderLabelsList))  # 设置行数目
        self.bill_parse_tableWidget.setColumnCount(initBillParseDialog.BILL_PARSE_COLUMN_COUNT)  # 设置列数目
        self.bill_parse_tableWidget.setHorizontalHeaderLabels(initBillParseDialog.BILL_PARSE_COLUMN_CONTEXT)

        self.bill_parse_tableWidget.resizeRowsToContents()  # 设置行宽自适应
        #self.alipay_bill_tableWidget.resizeColumnsToContents()  # 设置列宽自适应
        self.bill_parse_tableWidget.setShowGrid(True)  # 设置显示网络线
        self.bill_parse_tableWidget.setAlternatingRowColors(True)  # 设置表格颜色交错显示
        self.bill_parse_tableWidget.verticalHeader().setVisible(False)  # 隐藏垂直标题
        self.bill_parse_tableWidget.horizontalHeader().setStretchLastSection(True)  # 设置最后一列自动填充容

        self.bill_parse_tableWidget.setSelectionBehavior(QAbstractItemView.SelectRows)  # 设置选中整行
        self.bill_parse_tableWidget.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)  # 禁止编辑单元格

        self.bill_parse_tableWidget.setColumnWidth(0, 80)
        self.bill_parse_tableWidget.setColumnWidth(1, 180)
        self.bill_parse_tableWidget.setColumnWidth(2, 180)
        self.bill_parse_tableWidget.setColumnWidth(3, 500)
        self.bill_parse_tableWidget.setColumnWidth(4, 100)


    def initBillTableData(self):
        '''
        函数功能：对异常账单表的数据进行初始化
        :return:
        '''
        logger.debug("call initBillTableData function")
        # self.showAlipayBillData()
        self.showBillParesData()

    def showBillParesData(self):
        '''
        函数功能：展示要解析的账单假数据
        :return:
        '''

        tableLineCount = len(self.tableHeaderLabelsList)

        for i in range(tableLineCount):

            noStr = "%d\t"%(i+1)
            noItem = QTableWidgetItem(noStr)
            self.bill_parse_tableWidget.setItem(i, 0, noItem)


            titleItem = QTableWidgetItem(self.tableKeysList[i])
            self.bill_parse_tableWidget.setItem(i, 1, titleItem)

            headlineItem = QTableWidgetItem(self.tableHeaderLabelsList[i])
            self.bill_parse_tableWidget.setItem(i, 2, headlineItem)

            valueItem = QTableWidgetItem(self.tableValesList[i])
            self.bill_parse_tableWidget.setItem(i, 3, valueItem)



            widget = QWidget()
            widget.checkbox = QCheckBox()  # 将checkbox放在widget中
            #widget.checkbox.setCheckState(Qt.Checked)  # 默认全部勾选
            widget.checkbox.setCheckState(Qt.Unchecked)
            playout = QHBoxLayout(widget)
            playout.addWidget(widget.checkbox)  # 为小部件添加checkbox属性
            playout.setAlignment(Qt.AlignCenter)  # 设置小控件水平居中
            widget.setLayout(playout)  # 在QWidget放置布局


            self.bill_parse_tableWidget.setCellWidget(i, 4, widget)

        self.bill_parse_tableWidget.resizeRowsToContents()



    def getCheckListResult(self):
        '''
        函数功能：获取checkbox勾选的结果
        '''
        tableLineCount = len(self.tableHeaderLabelsList)
        checkList = []
        checkResult={}
        for countlength in range(tableLineCount):
            checkcount = self.bill_parse_tableWidget.cellWidget(countlength, 4).checkbox.isChecked()
            checkList.append(checkcount)
            if (checkcount==True):
                checkResult[self.tableKeysList[countlength]] = self.tableValesList[countlength]

        logger.debug("checkList:%s"%str(checkList))
        logger.debug("checkResult:%s" % str(checkResult))
        return checkList,checkResult

    def onOk(self):
        '''
        函数功能：响应确认按钮
        :return:
        '''
        logger.debug("call onOk function")

        self.AddOneBillRegulation()



        self.close()


    def onCancel(self):
        '''
        函数功能：响应取消按钮
        :return:
        '''
        logger.debug("call onCancel function")
        self.close()

    def showVoucherTreeInfo(self, subjectJsonTree):
        '''
        函数功能：展示指定的科目信息数据树
        :param subjectJsonTree:
        :return:
        '''

        self.subject_treeWidget.clear()
        self.subject_treeWidget.setColumnCount(1)
        self.subject_treeWidget.setItemsExpandable(True)
        logger.debug(subjectJsonTree)
        treeContextInfo = json.loads(subjectJsonTree)
        logger.debug(treeContextInfo)
        for key in treeContextInfo.keys():
            rootTreeWidgetItem = QTreeWidgetItem(self.subject_treeWidget)
            rootTreeWidgetItem.setText(0, key)
            if treeContextInfo[key] != "":
                self.parseVoucherTree(treeContextInfo[key], rootTreeWidgetItem)
            self.subject_treeWidget.addTopLevelItem(rootTreeWidgetItem)
            #end for

        self.subject_treeWidget.expandAll()

    def parseVoucherTree(self, dataDic, treeWidgetItem):
        '''
        将json数据结构映射到树形控件中
        :param dataDic:
        :param rootTreeWidgetItem:
        :return:
        '''

        for key in  dataDic.keys():
            oneTreeWidgetItem = QTreeWidgetItem(treeWidgetItem)
            oneTreeWidgetItem.setText(0, key)
            if dataDic[key]!="":
                self.parseVoucherTree(dataDic[key], oneTreeWidgetItem)


    def onSelectPropertyIncreaseSub(self):
        '''
        函数功能：响应资产增加科目输入框点击事件
        :return:
        '''
        logger.debug("call onSelectPropertyIncreaseSub function")

        self.currentVoucherTextEdit = self.property_increase_name_textEdit
        self.showVoucherTreeInfo(ConfigManage.readConfig("PROPERTY_NAME_JSON"))

    def onSelectPropertyDecreaseSub(self):
        '''
        函数功能：响应资产减少科目输入框点击事件
        :return:
        '''

        logger.debug("call onSelectPropertyDecreaseSub function")
        self.currentVoucherTextEdit = self.property_decrease_name_textEdit
        self.showVoucherTreeInfo(ConfigManage.readConfig("PROPERTY_NAME_JSON"))

    def onSelectOwnershipIncreaseSub(self):
        '''
        函数功能：响应权属增加科目输入框点击事件
        :return:
        '''
        logger.debug("call onSelectOwnershipIncreaseSub function")
        self.currentVoucherTextEdit = self.ownership_increase_name_textEdit
        self.showVoucherTreeInfo(ConfigManage.readConfig("OWNERSHIP_NAME_JSON"))


    def onSelectOwnershipDecreaseSub(self):
        '''
        函数功能：响应权属减少科目输入框点击事件
        :return:
        '''

        logger.debug("call onSelectOwnershipDecreaseSub function")
        self.currentVoucherTextEdit = self.ownership_decrease_name_textEdit
        self.showVoucherTreeInfo(ConfigManage.readConfig("OWNERSHIP_NAME_JSON"))


    def onTreeItemDoubleClicked(self, item, column):
        '''
        函数功能：响应资产、权属结构树节点双击事件
        :return:
        '''

        currentItem = item
        fullPath = currentItem.text(0)
        while(currentItem.parent()!=None):
            currentItem = currentItem.parent()
            fullPath = currentItem.text(0) + "->" + fullPath
        logger.debug(fullPath)

        if self.currentVoucherTextEdit!=None:
            self.currentVoucherTextEdit.setText(fullPath)


    def AddOneBillRegulation(self):
        '''
        函数功能：添加一条账单解析规则
        :return:
        '''
        curBillType = initBillParseDialog.BILL_TYPE_LIST[0]
        curSummary = self.summary_textEdit.toPlainText()
        curPropertyIncreaseName = self.property_increase_name_textEdit.toPlainText()
        curPropertyDecreaseName = self.property_decrease_name_textEdit.toPlainText()
        curOwnershipIncreaseName = self.ownership_increase_name_textEdit.toPlainText()
        curOwnershipDecreaseName = self.ownership_decrease_name_textEdit.toPlainText()
        rulePriority= self.priority_comboBox.currentIndex() + 1
        isMerge = self.merge_checkBox.isChecked()
        isValidBill = self.valid_checkBox.isChecked()


        checkList,checkResult=self.getCheckListResult()
        curRegulation=json.dumps(checkResult)

        billParseRegulationAlchemy = BillParseRegulationAlchemy(billType=curBillType,
                                                                summary=curSummary,
                                                                propertyIncreaseName=curPropertyIncreaseName,
                                                                propertyDecreaseName=curPropertyDecreaseName,
                                                                ownershipIncreaseName=curOwnershipIncreaseName,
                                                                ownershipDecreaseName=curOwnershipDecreaseName,
                                                                regulation=curRegulation,
                                                                priority=rulePriority,
                                                                isMerge=isMerge,
                                                                isValid=isValidBill
                                                                )

        billParseRegulationAlchemy.AddRegulationItem()

        QMessageBox.information(None, "通知", "账单解析规则添加成功",
                                QMessageBox.Ok)